import { LockOutlined, UserOutlined } from '@ant-design/icons'
import { useRequest } from 'ahooks'
import { Button, Checkbox, Form, Input, message } from 'antd'
import React, { useEffect, useState } from 'react'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
import { useRecoilState } from 'recoil'

import { loginByPwd } from '@/api/login'
import Footer from '@/layout/footer'
import { commonState } from '@/recoil'
// import {Icon} from '@/components/Icon'
const Login: React.FC<Record<string, never>> = () => {
  const navigate = useNavigate() //路由编程导航
  const [searchParams] = useSearchParams()

  const [isLogin, setIsLogin] = useRecoilState(commonState.isLogin)
  const [forget, setForget] = useState<boolean>(false) //忘记密码标志位
  // const routerParams = useParams()
  const location = useLocation()
  console.log('location', location)
  const { loading, runAsync } = useRequest(loginByPwd, {
    manual: true
  })
  useEffect(() => {
    // setForget(false)
    console.log(isLogin)
    // 实例化nc
    AWSC.use('nc', function (state, module) {
      const ncOption = {
        renderTo: 'awsc',
        appkey: 'FFFF0N0000000000A974',
        scene: 'nc_login',
        width: 340,
        //前端滑动验证通过时会触发该回调参数。您可以在该回调参数中将会话ID（sessionId）、签名串（sig）、请求唯一标识（token）字段记录下来，随业务请求一同发送至您的服务端调用验签。
        success: function (data: any) {
          window.console && console.log('data.sessionId:', data.sessionId)
          window.console && console.log('data.sig:', data.sig)
          window.console && console.log('data.token:', data.token)
        },
        // 滑动验证失败时触发该回调参数。
        fail: function (failCode: any) {
          window.console && console.log('failCode:', failCode)
        },
        // 验证码加载出现异常时触发该回调参数。
        error: function (errorCode: any) {
          window.console && console.log('errorCode:', errorCode)
        }
      } // 滑动验证初始化参数
      // 初始化 调用module.init对滑动验证进行初始化
      window.nc = module.init(ncOption)
    })
    // const nc = new noCaptcha(NC_Opt)
    // nc.upLang('cn', {
    //   _startTEXT: '请按住滑块，拖动到最右边',
    //   _yesTEXT: '验证通过',
    //   _error300:
    //     '哎呀，出错了，点击<a href="javascript:__nc.reset()">刷新</a>再来一次',
    //   _errorNetwork:
    //     '网络不给力，请<a href="javascript:__nc.reset()">点击刷新</a>'
    // })
  }, [])

  const onFinish = (values: any) => {
    runAsync({
      userName: values.username,
      password: values.password
    }).then((res) => {
      console.log('res', res)
      message.success('登陆成功')
      if (values.auto) {
        localStorage.setItem('token', JSON.stringify(res.data.token))
      } else {
        sessionStorage.setItem('token', JSON.stringify(res.data.token))
      }
      setIsLogin(true)
      const redirect = searchParams.get('redirect')
      navigate(redirect || '/')
    })
  }

  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }

  const changeStatus = () => {
    console.log(forget)
    setForget(true)
  }
  return (
    <div className="w-100% h-100% bg-#f1f2f6 flex flex-col justify-center items-center">
      <div className="w-340px m-auto text-center">
        <div className="text-34px ">
          <div className="font-black">
            <div>交通影响评价系统</div>
          </div>
        </div>
        <Form
          name="basic"
          style={{ flex: 1 }}
          initialValues={{ auto: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            className="mt-40px"
            name="username"
            rules={[{ required: true, message: '请输入账户名!' }]}
          >
            <Input size="large" placeholder="账户" prefix={<UserOutlined />} />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码!' },
              {
                pattern: /^\S{6,16}$/,
                message: '请输入6-16位密码,区分大小写'
              }
            ]}
          >
            <Input.Password
              size="large"
              placeholder="密码"
              prefix={<LockOutlined />}
            />
          </Form.Item>
          <Form.Item>
            <div id="awsc" style={{ position: 'inherit' }}></div>
          </Form.Item>
          <div className="flex justify-between">
            <Form.Item
              name="auto"
              valuePropName="checked"
              // wrapperCol={{ offset: 0, span: 16 }}
            >
              <Checkbox>自动登录</Checkbox>
            </Form.Item>
            <a style={{ lineHeight: '32px' }} onClick={changeStatus}>
              忘记密码
            </a>
          </div>
          <Form.Item
          // wrapperCol={{ offset: 0, span: 16 }}
          >
            <Button type="primary" htmlType="submit" block loading={loading}>
              登录
            </Button>
          </Form.Item>
          {/* <Form.Item>

              </Form.Item> */}
        </Form>
      </div>
      <Footer />
    </div>
  )
}
export default Login
